﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using MarginTrading.Entity;
using MarginTrading.Services;
using MarginTrading.Common;

namespace MarginTrading.site
{
    public partial class Login : System.Web.UI.Page
    {

        protected void Button2_Click(object sender, EventArgs e)
        {
            
                if (Username.Text == "" || Password.Text == "")
                {
                    labelLoginFailMsg.Text = "Enter Username and Password";
                    //MessageBox.Show("Please Enter Username and Password", "Enter Login Details", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return;
                }
                UserAccount User;
                try
                {
                    User = UserAccountServices.GetUserAccountByUserName(Username.Text);
                }
                catch (System.Exception ex)
                {
                    labelLoginFailMsg.Text = "Site temporally out of service";
                    return;
                }

                if (User == null)
                {

                    labelLoginFailMsg.Text = "Invalid Username or Password";
                    //MessageBox.Show("Invalid Username or Password", "Invalid Login", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    String sHashedPass = MD5Calculator.CalculateMD5Hash(Password.Text);

                    if (sHashedPass == User.Password)
                    {
                        //Program.currentUser = User;
                        Session["UserName"] = User.UserName;
                        Session["UserType"] = User.UserType;

                        if (Request.QueryString["RequestUrl"] != null)
                        {
                            Response.Redirect(Request.QueryString["RequestUrl"].ToString());
                        }
                        else
                        {
                            Response.Redirect("Default.aspx");
                        }
                        
                    }
                    else
                    {
                        labelLoginFailMsg.Text = "Invalid Username or Password";
                        //MessageBox.Show("Invalid Username or Password", "Invalid Login", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }


            
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //Username.Text = "user";
            //Password.Text = "abc123";
        }
    }
}
